import {RoomRendering, showPromptBtn} from "./Rendering.js"
import {upDateStateJwtKey} from "../localStorages/localStorageUesrData.js";
import {AddWaitingRoom, JoinWaitingRoom} from "../Axios/GameLobby.js";
import {showToast} from "../Toast.js"


// 添加房间按钮点击事件
document.getElementById('AddRoomSubmit').addEventListener('click', e => {
    let roomType = document.getElementById("roomType").value;
    let roomName = document.getElementById("roomName").value;
    let roomPassword = document.getElementById("roomPassword").value;
    let WaitingRoom = {
        "name": roomName, "type": roomType, "password": roomPassword
    };
    if (!roomPassword) {
        WaitingRoom = {
            "name": roomName, "type": roomType
        }
    }
    console.log(WaitingRoom)
    AddWaitingRoom(WaitingRoom).then(e => {
        console.log(e);
        window.location.href = `/WaitRoom.html`;
    })
    e.preventDefault();
});


// 玩家进入私有房间 获取密码 并 提交
document.getElementById('submitBtn').addEventListener('click', (ev) => {

    const inputForm = document.getElementById('inputForm');
    // 验证表单
    if (!inputForm.checkValidity()) {
        inputForm.classList.add('was-validated');
        return;
    }

    // 获取输入值
    const roomPassword = document.getElementById('room-password').value;
    let attribute = ev.target.getAttribute('data-roomUuid');

    JoinRoomRenderingPrompt({
        "roomId": attribute,
        "password": roomPassword
    })

    // 关闭弹框
    const modal = bootstrap.Modal.getInstance(document.getElementById('inputModal'));
    modal.hide();

    // 重置表单验证状态
    inputForm.classList.remove('was-validated');
})

// 玩家进入房间按钮点击事件
function buttonOnclick(ev) {
    // 获取房间的uuid
    let attribute = ev.target.getAttribute('data-roomUuid');
    // 获取房间类型
    let roomType = ev.target.getAttribute('data-roomType');

    // 如果私有需要获取房间密码
    if (roomType !== 'PUBLIC') {
        document.getElementById('submitBtn').setAttribute('data-roomUuid', attribute)
        showPromptBtn()
        return
    }
    // 玩家添加到房间
    JoinRoomRenderingPrompt({
        "roomId": attribute,
    })
}

// 玩家 加入房间 渲染提示框
function JoinRoomRenderingPrompt(data) {
    JoinWaitingRoom(data).then(() => {
        showToast("加入房间成功", "success")
        // 跳转到游戏房间
        window.location.href = `/WaitRoom.html`;
    }).catch(e => {
        showToast(e.response.data.message, 'error')
    })
}


// 初始渲染房间
async function renderRooms() {
    const token = (await upDateStateJwtKey()).count.jwtKey;

    /**
     * 列表查询房间
     * /ws/rooms/{current}/{limit}
     *
     * @param current current – 当前页
     * @param limit   limit – 每页显示条数
     */
    if ('WebSocket' in window) {
        const socket = new WebSocket("/ws/rooms/1/10", ["Bearer", token]);

        socket.onclose = function(event) {
            console.log('关闭代码:', event.code);
            console.log('关闭原因:', event.reason);
            console.log('是否干净关闭:', event.wasClean);
        };


        socket.onmessage = function (event) {
            console.log("WebSocket收到消息");

            let {data} = JSON.parse(event.data);
            console.log(data)
            RoomRendering(data, buttonOnclick);
        };


        // 上一页
        document.getElementById("prevPage").addEventListener("click", function () {
            let prevPageCurrent = data.current - 1

            if (prevPageCurrent < 1) {
                console.log("测试", prevPageCurrent)

                return;
            }

            socket.send(JSON.stringify({
                "total": data.total,
                "current": prevPageCurrent,
                "limit": data.limit
            }))
        })
        // 下一页
        document.getElementById("nextPage").addEventListener("click", function () {
            let nextPageCurrent = data.current + 1

            if (nextPageCurrent > data.total) {
                console.log("测试", nextPageCurrent)
                return;
            }

            socket.send(JSON.stringify({
                "total": data.total,
                "current": nextPageCurrent,
                "limit": data.limit
            }))
        })
        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            socket.close();
        }
    }
}

// 页面加载完成后渲染棋盘
window.onload = function () {
    renderRooms()
};